<template>
  <!-- 水质分析模板 -->
  <!-- 右侧内容 -->

  <div>
    <gongyong @serchClick="serchClick" ref="gongyong" :gongyongOption="gongyongOption">
      <!-- 顶部栏 -->
      <template #top-left>
        <div class="block">
          <!-- select下拉 一 -->

          <span class="date-text">工艺</span>
          <el-select style="width: 10%" v-model="craftslectValue" @change="selectChange" size="mini">
            <el-option v-for="item in craftoptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.disabled">
            </el-option>
          </el-select>
          <!-- select下拉 二 -->
          <span class="date-text" style="margin-left: 20px">参数</span>
          <el-select v-model="TypeslectValue" @change="selectChange2" style="width: 10%" size="mini">
            <el-option v-for="item in Typeslectoptions" :key="item.id" :label="item.name" :value="item.enName" :disabled="item.disabled">
            </el-option>
          </el-select>

          <!-- select下拉 选择多长时间 -->
          <span class="date-text" style="margin-left: 20px">时间</span>
          <el-select v-model="dateSlectValue" @change="dateSelectChange" style="width: 10%" size="mini">
            <el-option v-for="item in dateOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
            </el-option>
          </el-select>
          <!-- 时间 -->
          <span class="date-text" style="margin-left: 15px">操作时间</span>
          <el-date-picker size="mini" style="width: 25%" v-model="dateValue" type="daterange" range-separator="→" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" @change="dateChange">
          </el-date-picker>
        </div>
      </template>

      <!-- 中间图表 -->
      <template #centre>
        <div ref="myChart" :style="{ width: '100%', height: '270px' }" v-loading="loading"></div>
      </template>

      <!-- 下边的Table组件 -->
      <template #bottom>
        <deviceTable :dataList="dataList" :devTable="waterTableList" v-loading="loading">
          <!-- <template #tab-bttom>
            <tableBttom :dataList="dataList" :devTable="tabBtmList"></tableBttom>
          </template> -->
        </deviceTable>
      </template>
    </gongyong>
  </div>
</template>

<script>
import gongyong from "../layout/gongyong.vue"; // 共用模板
import echarts from "echarts"; // 引入eahers
import deviceTable from "@/views/waterAnalysi/components/deviceTable.vue";
import tableBttom from "@/views/waterAnalysi/components/tableBttom.vue";
// 水质分析接口
import {
  getCraft,
  getType,
  waterQualityList, // 获取水质数据
  waterAlarm, // 水质报警信息
} from "@/api/operationAnalysis/waterAnalysis/waterQuality ";
export default {
  components: {
    gongyong,
    deviceTable,
    tableBttom,
  },
  props: ["nodeData"],
  watch: {
    suoS: {
      handler (value) {
        
      },
      immediate: true,
      deep: true,
    },
    dateValue: {
      handler (newVal) {
        console.log(newVal);
        if (!newVal) {
          this.dateValue = [];
        }
      },
    },
  },

  data () {
    return {
      dateValue: "", // 绑定日期
      Typequery: {
        searchStartDate: "2022-01-01", // 日期绑定 开始时间
        searchEndDate: "", // 日期绑定 结束时间
      }, // 查询时间

      // searchType: {
      //   monitorPointId: "", // 监测点ID
      //   workmanshipId: "", // 水厂工艺id
      // },
      gongyongOption: {
        top: true,
        center: true,
        bottom: true,
        rest: true, // 重置按钮
      }, // 公用组件配置

      suoS: {
        monitorPointId: "", // 监测点ID
        workmanshipId: "", // 水厂工艺id
        minutes : 1, // 间隔分钟
      }, //查询条件
      // 工艺-------------------------
      craftslectValue: "", // 下拉框
      loading: true,

      craftoptions: [], // 工艺下拉配置
      waterList: [], // 水质数据
      waterTableList: [],
      typeKey: "", // 类型下拉 记录

      // 类型-----------------------------
      TypeslectValue: "", // 下拉框
      sleTypeData: {}, // 存放当前选中类型的数据
      Typeslectoptions: [],
      // 间隔时间-----------------------------
      dateSlectValue: "一分钟", // 下拉框

      dateOptions: [
        {
          value: 1,
          label: "一分钟",
        },
        {
          value: 5,
          label: "五分钟",
        },
        {
          value: 10,
          label: "十分钟",
        },

        {
          value: 60,
          label: "一小时",
        },
      ],
      searchStartDate: "2022-01-01", // 日期绑定 开始时间
      searchEndDate: "2022-03-11", // 日期绑定 结束时间
      // 数据列表的配置对象
      dataList: [],
      tabBtmList: [
        {
          createDate: "平均值",
          rawDissolvedOxygen: "王小虎",
        },
        {
          createDate: "最大值",
          rawDissolvedOxygen: "王小虎",
        },
        {
          createDate: "最小",
          rawDissolvedOxygen: "王小虎",
        },
        {
          createDate: "总计",
          rawDissolvedOxygen: "王小虎",
        },
      ],
    };
  },
  created () {
    this.newdata();
    this.Typequery.searchStartDate = this.Typequery.searchStartDate;
  },
  mounted () {
    this.suoS.monitorPointId = this.$parent.$parent.$parent.nodeData
    if (this.suoS.monitorPointId || this.$parent.$parent.$parent.nodeData) {
      this.getCraftSelect(this.suoS.monitorPointId)
    }
    // if (
    //   (this.suoS.monitorPointId && this.suoS.workmanshipId) ||
    //   (this.$parent.$parent.$parent.nodeData.id && this.suoS.workmanshipId)
    // ) {
    //   this.$refs.gongyong.serchClick(); // 调用一次公共组件搜索按钮
    // } else {
    //   setTimeout(() => {
    //     this.$refs.gongyong.serchClick();
    //   }, 1000);
    // }
    this.drawLine(); // echarts创建
  },
  methods: {
    drawLine (
      deviceName,
      createDate,
      titleName,
      alertLowest,
      alertLow,
      alertHigh,
      alertHighest
    ) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(this.$refs.myChart);
      // 绘制图表

      let option = {
        title: {
          text: titleName,
          // padding: [20, 20, 100, 100],
        },

        xAxis: {
          type: "category",
          data: createDate,
          // axisLabel: {
          //   interval: 0,
          // },
        },
        yAxis: {
          type: "value",
        },
        tooltip: {
          trigger: "axis",
        },
        grid: {
          x: 45,
          x2: 35,
          y: 45,
          y2: 35,
        },
        series: [
          {
            name: "当前值",
            type: "line",
            data: deviceName,
            color: "#0079fe",
            lineStyle: {
              color: "#0079fe", //改变折线颜色
            },
          },
          {
            name: "最低线",
            type: "line",
            data: alertLowest,
            color: "#006400",
            lineStyle: {
              color: "#006400", //改变折线颜色
            },
          },
          {
            name: "低限",
            type: "line",
            data: alertLow,
            color: "#99fb98",
            lineStyle: {
              color: "#99fb98", //改变折线颜色
            },
          },
          {
            name: "高限",
            type: "line",
            data: alertHigh,
            color: "#feb6c1",
            lineStyle: {
              color: "#feb6c1", //改变折线颜色
            },
          },
          {
            name: "最高限",
            type: "line",
            data: alertHighest,
            color: "#db133c",
            lineStyle: {
              color: "#db133c", //改变折线颜色
            },
          },
        ],
        legend: {
          x: "center", //可设定图例在左、右、居中
          y: "bottom", //可设定图例在上、下、居中
          padding: [20, 0, 0, 0],
        },
      };
      myChart.setOption(option);

      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },
    // 获取工艺下拉数据
    async getCraftSelect (id) {
      let obj = {
        monitorPointId: id
      }
      const { data } = await getCraft(obj);
      this.craftoptions = data;
      // console.log(this.craftoptions);
      this.craftslectValue = this.craftoptions[0].name;
      this.suoS.workmanshipId = this.craftoptions[0].id;
      this.getTypeSelect();
      this.getWaterQualityList();
    },
    // 获取类型下拉数据
    async getTypeSelect () {
      let obj = {
        monitorPointId : this.suoS.monitorPointId,
        workmanshipId : this.suoS.workmanshipId,
        paramMark : 1
      }
      const { data } = await getType(obj);
      this.TypeslectValue = "";
      this.Typeslectoptions = data;
      if (this.Typeslectoptions.length < 1) {
        return;
      }
      // console.log(this.Typeslectoptions);
      this.TypeslectValue = this.Typeslectoptions[0].name;
      this.typeKey = this.Typeslectoptions[0].enName;
      this.sleTypeData.name = this.Typeslectoptions[0].name;
      this.sleTypeData.id = this.Typeslectoptions[0].id;
      this.tabTiltie(data);
    },

    // // 获取警戒线
    // async getwaterAlarm() {
    //   let res = await waterAlarm({
    //     deviceParameterId: this.sleTypeData.id,
    //   });
    //   console.log(res.data);
    // },

    // 处理Tba表头
    tabTiltie (waList) {
      let defarray = waList;
      // console.log(defarray);
      let newTab = [];
      let defnum = 1;
      defarray.forEach((item, index) => {
        defnum = index + 2;
        newTab.push({
          id: defnum,
          prop: item.enName,
          label: item.name + `(${item.unit})`,
        });
      });
      let defdate = {
        prop: "colname",
        label: "时间",
        id: 1,
      };
      newTab.unshift(defdate);
      console.log(newTab);
      this.dataList = newTab;
    },

    // 工艺
    selectChange (label) {
      this.suoS.workmanshipId = label;
      this.getTypeSelect();
    },
    // 类型
    selectChange2 (label) {
      this.typeKey = label;
      // console.log(this.typeKey);
      // console.log(this.Typeslectoptions);
      let sleTypeData = this.Typeslectoptions.filter(function (item) {
        return item.enName === label;
      });
      this.sleTypeData = sleTypeData[0];
      // console.log(this.sleTypeData);
    },

    // 间隔时间
    dateSelectChange (label) {
      this.suoS.minutes = label;
    },

    newdata () {
      //获取当前时间
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      if (month < 10) {
        undefined;
        month = "0" + month;
      }
      if (day < 10) {
        undefined;
        day == "0" + day;
      }
      this.Typequery.searchEndDate = year += "-" + month + "-" + day;
      // console.log(this.Typequery.searchEndDate);
    },
    // 日期选择
    dateChange () {
      // console.log(this.dateValue);
      if (!this.dateValue) {
        this.dateValue = [];
      }
      this.Typequery.searchStartDate = this.dateValue[0];
      this.Typequery.searchEndDate = this.dateValue[1];
      console.log("开始时间" + this.Typequery.searchStartDate);
      console.log("结束时间" + this.Typequery.searchEndDate);
    },
    // 点击重置按钮
    // resetClick() {
    //   this.dateValue = "";
    // },
    // 搜索按钮触发事件
    async serchClick () {
      console.log("搜索按钮触发事件");
      if (!this.Typequery.searchStartDate && !this.Typequery.searchEndDate) {
        console.log("请选择查询时间");
        this.$message.error("请选择查询时间");
        return;
      }
      this.suoS = { ...this.suoS, ...this.Typequery };
      // console.log(this.sleTypeData);
      // this.getWaterQualityList();
    },

    // 获取水质数据
    async getWaterQualityList () {
      let obj = {
        searchDateStart : "2022-07-17",
        searchDateEnd : "2022-07-18",
        monitorPointId : this.suoS.monitorPointId,
        workmanshipId : this.suoS.workmanshipId
      }
      if (!this.suoS.monitorPointId) {
        console.log("请选择监测点");
        this.$message.error("请选择监测点");
        this.loading = false;
        return;
      }
      try {
        const res = await waterQualityList(obj);
        if (res.code !== 20000) {
          return this.$message.error(res.message);
        }
        this.waterTableList = res.data
        this.waterList = res.data;
        this.waterList.length = this.waterList.length - 5
        let defArray = this.waterList.map((item) => {
          if(item[this.typeKey]){
            return item[this.typeKey]
          }
        }); // 当前时间
        let defRun = this.waterList.map((item) => {
          if(item.colname) {
            return item.colname.substring(item.colname.length - 14)
          }
        }); // 当前时间

        // // 获取警戒线
        let jingres = await waterAlarm({
          deviceParameterId: this.sleTypeData.id,
        });
        let defList = jingres.data;
        console.log(defList)
        debugger;
        let warningLine = {
          alertLowest: [], //最低线
          alertLow: [], // 底限
          alertHigh: [], //高限
          alertHighest: [], //最高线
        }; // 存放警告线
        if (defList.length > 0) {
          this.waterList.forEach((item) => {
            warningLine.alertLowest.push(defList[0].alertLowest);
            warningLine.alertLow.push(defList[0].alertLow);
            warningLine.alertHigh.push(defList[0].alertHigh);
            warningLine.alertHighest.push(defList[0].alertHighest);
          });
          console.log(warningLine)
          debugger;
        }
        // console.log(warningLine);

        this.drawLine(
          defArray,
          defRun,
          this.sleTypeData.name,
          warningLine.alertLowest,
          warningLine.alertLow,
          warningLine.alertHigh,
          warningLine.alertHighest
        ); // 刷新echarts
        this.loading = false;

        this.$message.success(res.message);
      } catch (err) {
        this.loading = false;
      }

      // console.log(this.waterList);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-date-editor .el-range-separator {
  padding: 0px 0px;
}
.date-text {
  font-size: 14px;
}
// .rightcontant {
//   width: 85.8%;
// }
// .rightcontant2 {
//   width: 97%;
// }
</style>
